<template>
  <div>
    <span
      v-for="el in data"
      :key="el.value"
      class="inline-block rounded border border-solid px-5 py-1.5 text-sm mr-4.5 cursor-pointer"
      :class="[getTypeClass(el.selected)]"
      @click="selectItem(el)"
    >
      {{ el.label }}
    </span>
  </div>
</template>
<script lang="ts" setup>
import type { SelectOptionItem } from "/@/types/antd";
import { watch } from "vue";

const props = defineProps<{
  data: SelectOptionItem[];
  type?: "default";
  modelValue?: (number | string) | (number | string)[];
}>();
const emits = defineEmits(["update:modelValue"]);
function getTypeClass(selected: boolean | undefined) {
  switch (props.type) {
  }
  return selected
    ? "bg-color-active text-white border-color-active"
    : "bg-color-gray text-color-secondary border-color-gray";
}

function clearSelected() {
  props.data.forEach((el) => {
    el.selected = false;
  });
}
function getSelectedValues() {
  const values: SelectOptionItem["value"][] = [];
  props.data.forEach((el) => {
    if (el.selected) {
      values.push(el.value);
    }
  });
  return values;
}
function isMultiple() {
  return Array.isArray(props.modelValue);
}
function selectItem(el) {
  if (isMultiple()) {
    el.selected = !el.selected;
    emits("update:modelValue", getSelectedValues());
  } else {
    if (el.selected) return;
    clearSelected();
    el.selected = true;
    emits("update:modelValue", el.value);
  }
}
watch(
  () => props.modelValue,
  (v) => {
    clearSelected();
    if (isMultiple()) {
      props.data.forEach((el) => {
        if ((v as SelectOptionItem["value"][]).includes(el.value)) {
          el.selected = true;
        }
      });
    } else {
      const item = props.data.find((el) => el.value === v);
      if (item) {
        item.selected = true;
      }
    }
  },
  {
    immediate: true,
  }
);
</script>
